package com.study.druid.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
 * @ClassName TwoConfig
 * @Author swj
 * @Date 2020/9/3 11:01
 */
@Configuration
@MapperScan(basePackages = "cn.nx.demo.dao.two",
        sqlSessionFactoryRef = "sqlSessionFactoryTwo",
        sqlSessionTemplateRef = "sqlSessionTemplateTwo")

public class TwoConfig {

    private DataSource twoDataSource;

    public TwoConfig(@Qualifier("twoDataSource") DataSource twoDataSource){
        this.twoDataSource = twoDataSource;
    }


    @Bean
    public SqlSessionFactory sqlSessionFactoryTwo() throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(twoDataSource);
        sqlSessionFactoryBean.setTypeAliasesPackage("cn.nx.demo.entity.two");
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath:mapper/two/*.xml"));

        //配置驼峰转换和其他配置
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        configuration.setMapUnderscoreToCamelCase(true);
        sqlSessionFactoryBean.setConfiguration(configuration);
        return sqlSessionFactoryBean.getObject();
    }

    @Bean
    public SqlSessionTemplate sqlSessionTemplateTwo() throws Exception {
        return new SqlSessionTemplate(sqlSessionFactoryTwo());
    }


}
